<template>
    <el-button :disabled="countDisabled" @click="getCode">{{ countText }}</el-button>
</template>
<script lang="ts" setup>
import { ref } from 'vue'
import { ElMessage } from 'element-plus'
import { SendPhoneCode } from '@/api/user'

const props = defineProps({
    phone: {
        type: String,
        default: '',
    },
    type: {
        type: Number,
        default: 1,
    }
});

const countDisabled = ref(false)
const countText = ref('获取验证码')

const getCode = () => {
    if(props.phone === '') {
        ElMessage.error('请输入手机号')
        return
    }
    if (!/^1[3456789]\d{9}$/.test(props.phone)) {
        ElMessage.error('手机号格式不正确')
        return
    }
    countDisabled.value = true
    SendPhoneCode({
        mobile: props.phone,
        type: props.type
    }).then(() => {
        ElMessage.success('发送成功')
        let currentTime = 60
        countText.value = '60S重新获取'
        let interval = setInterval(() => {
            currentTime--
            countText.value = currentTime + 'S' + '重新获取'
            if (currentTime <= 0) {
                clearInterval(interval)
                countText.value = '重新获取'
                countDisabled.value = false
            }
        }, 1000)
    })
}
</script>
<style lang="sass" scoped>

</style>